package locks.solve.cooperating;

import annotation.GuardedBy;
import annotation.ThreadSafe;
import locks.entity.Image;

import java.util.HashSet;
import java.util.Set;

/**
 * 出租车车队
 * 只要锁住有线程安全问题的地方，然后解锁，使双锁变成单锁
 */
@ThreadSafe
public class Dispatcher {
    @GuardedBy("this")
    private final Set<Taxi> taxis;
    @GuardedBy("this")
    private final Set<Taxi> availableTaxis;

    public Dispatcher() {
        taxis = new HashSet<Taxi>();
        availableTaxis = new HashSet<Taxi>();
    }

    /**
     * 通知到达指定集合地点
     * @param taxi
     */
    public synchronized void notifyAvailable(Taxi taxi) {
        availableTaxis.add(taxi);
    }


    /**
     * 添加车队
     * @param taxi
     */
    public void addTaxis(Taxi taxi){
        taxis.add(taxi);
    }

    /**
     * 获取 车队中所有出租车位置
     * @return
     */
    public Image getImage() {
        Set<Taxi> copy;
        //将有可能被改动的地方单独锁起来
        synchronized (this){
            copy = new HashSet<>(taxis);
        }
        Image image = new Image();
        for (Taxi t : copy)
            image.drawMarker(t.getLocation());
        return image;
    }

}